<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends MY_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model('User_model');
	}
	public function index()
	{
		$this->load->template('user_signup');
	}
        
    
	public function login()
	{
		$username = $this->input->post('username');
		$password = $this->input->post('password');

		$this->load->model('User_model');
		
		$this->load->helper('email');
		
		$isemail = valid_email($username);
 
        $userinfo = $this->User_model->login($username,$password,$isemail);
		
		if($userinfo)	
		{
			//设置session变量
			$this->session->set_userdata(array('uid'=>$userinfo['uid'],'username'=>$userinfo['username'],'roleid'=>$userinfo['roleid']));
			//跳转到控制台
			redirect('c=home&m=index', 'refresh');
		}
		$userinfo['message']="登录失败，用户名或密码错误！";
		$this->load->template('user_signup',$userinfo);
	}

	public function logout()
	{
		$this->session->set_userdata(array('uid'=>0,'username'=>'','roleid'=>0));
		redirect('c=home&m=index', 'refresh');
	}

	//用户注册
	public function register()
	{

		$this->form_validation->set_rules('username', '用户名', 'required');
		$this->form_validation->set_rules('password', '密码', 'required');
		$this->form_validation->set_rules('password2', '密码确认', 'required');
		$this->form_validation->set_rules('email', '注册邮箱', 'required');
		
		$registersubmit = $this->input->post('registersubmit');
		$resultinfo['method'] ='add';

		if($registersubmit  && $this->form_validation->run())
		{
			
			$data['username'] = $this->input->get_post('username');
			$data['email'] = $this->input->get_post('email');
			$data['password'] = $password = $this->input->get_post('password');
			$data['regdate'] =time();
			$password2 = $this->input->get_post('password2');
			$checkresult =true;
			if($checkresult = $this->User_model->check_unique($username,$email))
			{
				$userinfo = $this->User_model->insert_user($data);
				
			  //设置session变量
				$this->session->set_userdata(array('uid'=>$userinfo['uid'],'username'=>$userinfo['username'],'roleid'=>$userinfo['roleid']));
	
				$this->show_message("新增用户信息成功",site_url("c=user&m=index"));
			}
			else
			{
				$this->show_message("注册失败",site_url("c=user&m=index"));
			}
		}
		else
		{		
			$this->load->template('user_signup',$userinfo);
		}
	}

	//判断用户名是否唯一，返回json对象
	public function unique()
	{
		$uid = intval($this->input->get_post('uid'));
		$username = $this->input->get_post('username');
		$email = $this->input->get_post('email');
		$result['status'] =1;
		$result['success'] = $this->User_model->check_unique($username,$email,$uid);
		$this->load->library('json');
		echo $this->json->encode($result);
	}

}